<template>
  <div style="height: 800px;">
      <div style="float:right">
        <template >
          <el-button size="mini" type="danger" @click="startGame()">开始游戏</el-button>
      </template>
      <template >
          <el-button size="mini" type="danger" @click="getAnswer()">查看答案</el-button>
      </template>
      <div style="float: right;position: absolute;top:150px ">
        <span v-if="isScore" >得分:{{score}}</span>
        <span v-if="isShow" >最小步数:{{count}}</span>
      <span style="margin-right:20px">用时:{{time}}秒</span>
    </div>
      <el-form v-if="tableShow" :disabled="isTable" :model="numberValidateForm" ref="numberValidateForm" label-width="100px" class="demo-ruleForm" style="position: absolute;right: 10px;top: 200px;">
  <el-form-item
    label="步数"
    prop="age"
    :rules="[
      { required: true, message: '不能为空'},
      { type: 'number', message: ''}
    ]"
  >
    <el-input v-model.number="numberValidateForm.age" autocomplete="off"></el-input>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="submitForm(numberValidateForm)">提交</el-button>
  </el-form-item>
</el-form>
      
      </div>
      <div id="gameId" ref="container" style="position: absolute;right: 600px;top: 200px;">
    
  </div  >
      <div > 
        <span style="width: 50%;">最近10局记录</span>
        <el-table
      :data="gameList"
      style="width: 500px">
      <el-table-column
        prop="createTime"
        label="时间"
        width="180">
      </el-table-column>
      <el-table-column
        prop="duration"
        label="时长(秒)"
        width="180">
      </el-table-column>
      <el-table-column
        prop="score"
        label="得分">
      </el-table-column>
    </el-table>
    <!-- <span>游戏平均分排名</span>
        <el-table
      :data="avgData"
      style="width: 500px">
      <el-table-column
        prop="index"
        label="序号"
        width="180">
      </el-table-column>
      <el-table-column
        prop="name"
        label="姓名"
        width="180">
      </el-table-column>
      <el-table-column
        prop="avgScore"
        label="平均分">
      </el-table-column>
    </el-table> -->

  </div>
  </div>
</template>
<script type="text/ecmascript-6">
import Maze from "../../api/Maze.js";
import {getList,insert} from "../../api/game.js";
export default {
  data() {
    return {
      
      //建议15   25   45
      numberValidateForm:{
          age: ''
        },
      intervalId:"",
      isShow:false,
      isScore:false,
      count: 0,
      score:0,
      time: 0,
      startX: 25,
      stratY: 25,
      mazeHas:{},
      isTable:false,
      tableShow:false,
      gameList:[]
    };
  },
  mounted() {
    // this.oneAgain(1);
    this.getGameList();
  },
  methods: {
    getGameList(){
      let param = {}
      param.pageIndex =0;
      param.pageSize=10;
      getList(param).then(res=>{
         if(res.status==200){
            this.gameList = res.data;
         }else{
          this.$message({
            type: "error",
            message: "获取对局记录失败"
          });
         }
      })
    },
    submitForm(formName) {
      clearInterval(this.intervalId)
        let param = {};
        param.age = formName.age;
        let absNum = Math.abs(this.count - param.age)
        let percentage = Math.floor((absNum/this.count)*100);
        let score = 100 - percentage;
        if(score<0){
            score = 0;
        }
        console.log("========score:"+score)
        this.score = score;
        param.score = score;
        param.duration = this.time;
        insert(param).then(res=>{
          if(res.status==200){
            this.getGameList();
         }else{
          this.$message({
            type: "error",
            message: "对局失败"
          });
        }
        })
        this.isScore = true;
        this.isTable = true;
    },
    
    shortestPath(maze, start, end) {
      let rows = maze.length;
      let cols = maze[0].length;
      //定义方向
      let directions = [
        [0, 1], //向下走一步，
        [0, -1], //向上走一步
        [1, 0], //向右走一步
        [-1, 0] //向左走一步
      ];
      let visited = Array.from(Array(rows), () => Array(cols).fill(false));
      let queue = [[start, 0, []]];
      while (queue.length > 0) {
        let [[X, Y], steps, path] = queue.shift();
        if (X === end[0] && Y === end[1]) {
          return [steps, path.concat([[X, Y]])];
        }
        for (let dir of directions) {
          let [dx, dy] = dir;
          let newX = X + dx;
          let newY = Y + dy;
          if (
            newX >= 0 &&
            newX < rows &&
            newY >= 0 &&
            newY < cols &&
            maze[newX][newY] == 0 &&
            !visited[newX][newY]
          ) {
            visited[newX][newY] = true;
            queue.push([[newX, newY], steps + 1, path.concat([[X, Y]])]);
          }
        }
      }
      return [-1, []];
    },
    startGame(){
      this.isScore = false;
      this.tableShow = true,
      this.numberValidateForm.age = '',
      this.isTable = false,
      clearInterval(this.intervalId)
      this.isShow=false,
      this.oneAgain()
      this.intervalId = setInterval(() => {
        this.time++;
        }, 1000);
    },

    getAnswer(){
      this.isShow=true,
      this.isTable = true;
      clearInterval(this.intervalId)
      this.mazeHas.findPath();
    },
    oneAgain() {
      this.$refs.container.innerHTML='';
      this.count = 0;
      this.time = 0;
      let mazeHasDown = new Maze(this.startX, this.stratY, 5, 400, 400).initMaze();
    //   if(type == 2){
    //     this.$refs.container.removeChild(this.$refs.mazes)
    //   }   
      this.$refs.container.appendChild(mazeHasDown.html);
      mazeHasDown.paintMaze();
      this.mazeHas = mazeHasDown;
      let start = [this.mazeHas.entryX, this.mazeHas.entryY]; // 起点坐标
      let end = [this.mazeHas.outX, this.mazeHas.outY]; // 终点坐标
      let [steps, path] = this.shortestPath(this.mazeHas.maze, start, end); // 调用函数计算最短路径
      if (steps !== -1) {
        this.count = steps;
        console.log(`最短步数为：${steps}`); // 输出最短步数
      } else {
        console.log("未找到路径"); // 输出未找到路径的提示
      }
    }
  }
};
</script>

<style scoped>
</style>
